<template>
  <div class="content">
    <div class="pageLeft">
      <div class="oeeReportSearch">
        <el-form :inline="true" :model="searchParam">
          <!-- <el-form-item label="车间">
            <el-input v-model="searchParam.no" placeholder="请输入车间" clearable style="width: 200px" />
          </el-form-item> -->
          <el-form-item label="Equipment">
            <el-select v-model="searchParam.equipmentId" clearable filterable placeholder="请选择设备" style="width: 250px">
              <el-option v-for="item in deviceList" :key="item.id" :label="item.equipmentCode" :value="item.id">
                <span style="float: left">{{ item.equipmentCode }}</span>
                <span style="
                    float: right;
                    color: var(--el-text-color-secondary);
                    font-size: 13px;
                  "> {{ item.equipmentName }} </span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="Date">
            <el-date-picker v-model="searchParam.date" type="date" placeholder="请选择时间" value-format="YYYY-MM-DD"
              style="width: 200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="oeeReportBody">
        <div class="oeeReportView">
          <div class="pageTableTitle"> OEE </div>
          <div style="width: 100%;height: calc(100% - 20px);display: flex;">
            <div ref="OEEChart" id="OEEChart" style="width:65%;height: 100%;"></div>
            <div class="leftTopView">
              <div class="left-view">
                <div class="leftTopView-label">AV</div>
                <div class="leftTopView-value">{{ OEELineChartParam.av[infoLength - 1] }}%</div>
              </div>
              <div class="left-view">
                <div class="leftTopView-label">Performance</div>
                <div class="leftTopView-value">{{ OEELineChartParam.performance[infoLength - 1] }}%</div>
              </div>
              <div class="left-view">
                <div class="leftTopView-label">Quality</div>
                <div class="leftTopView-value">{{ OEELineChartParam.quality[infoLength - 1] }}%</div>
              </div>
            </div>
          </div>
        </div>
        <div class="oeeReportView">
          <div class="pageTableTitle"> AV </div>
          <div ref="timeChart" id="timeChart" style="width: 100%;height: calc(100% - 20px)">
          </div>
        </div>
      </div>
      <div class="oeeReportBody">
        <div class="oeeReportView">
          <div class="pageTableTitle"> Performance </div>
          <div ref="perChart" id="perChart" style="width: 100%;height: calc(100% - 20px)">
          </div>
        </div>
        <div class="oeeReportView">
          <div class="pageTableTitle"> Quality </div>
          <div ref="YIELDChart" id="YIELDChart" style="width: 100%;height: calc(100% - 20px)">
          </div>
        </div>
      </div>
      <div class="oeeReportBody">
        <div class="oeeReportView" style="width: 100%;">
          <div class="pageTableTitle"> OEE </div>
          <div ref="OEELineChart" id="OEELineChart" style="width: 100%;height: calc(100% - 20px)">
          </div>
        </div>
      </div>
    </div>
    <div class="pageRight">
      <!-- OEE排行榜 -->
      <div class="oeeTop">
        <div class="pageTableTitle"> OEE Top </div>
        <el-table :data="topTable" header-cell-class-name="witheTableHeader" height="100%">
          <el-table-column label="Top" type="index" align="center" width="80">
            <template #default="scope">
              <div style="display: flex;align-items: center;justify-content: center;">
                <div :class="'cell index-' + (scope.$index + 1)" v-if="scope.$index + 1 > 3">{{ scope.$index + 1 }}
                </div>
                <img v-else-if="scope.$index + 1 == 1" class="responsive-image" src="../report/image/top1.png">
                <img v-else-if="scope.$index + 1 == 2" class="responsive-image" src="../report/image/top2.png">
                <img v-else-if="scope.$index + 1 == 3" class="responsive-image" src="../report/image/top3.png">
              </div>
            </template>
          </el-table-column>
          <el-table-column label="EquipmentCode" prop="equipmentCode" align="center" show-overflow-tooltip />
          <el-table-column label="OEE" prop="oee" align="center" width="100">
            <template #default="scope"> {{ scope.row.oee }} % </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import SearchForm from '@/components/SearchForm.vue';
import axiosInstance from '@/utils/http/api';
import { Delete, Edit, Plus, Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import moment from 'moment';

onMounted(() => {
  // getList();
  getTopList()
  getOptions()
});
const topTable = ref([])
const pageList = ref({});
const OEEChart = ref(null)
const timeChart = ref(null)
const perChart = ref(null)
const YIELDChart = ref(null)
const OEELineChart = ref(null)

// 日期列表
const dateList = ref([])

// AV参数
const timeChartParam = ref({
  devicePlanRunTime: [],//Planned production time
  deviceRealRunTime: []//Actual running time
})

// Perfommance参数
const perChartParam = ref({
  deviceTheoryRunTime: [],//Target CT
  deviceRealRunTime: [],//Actual running time
})

// Quality参数
const YIELDChartParam = ref({
  reportTotalCount: [],//Actual total output
  reportPassCount: [],//Actual OK output
})

// OEE趋势图参数
const OEELineChartParam = ref({
  oee: [],//OEE
  av: [],//AV
  performance: [],//Perfommance
  quality: []//Quality
})

const infoLength = ref(0)

const getList = () => {
  if (!searchParam.value.equipmentId) {
    ElMessage.warning('请选择设备')
    return false
  }

  if (!searchParam.value.date) {
    ElMessage.warning('请选择时间')
    return false
  }

  axiosInstance.post("/api/oeeReport/list ", searchParam.value)
    .then((res) => {
      if (res.code !== 200) {
        ElMessage.error(res.message);
        return false;
      }
      timeChartParam.value.devicePlanRunTime = []
      timeChartParam.value.deviceRealRunTime = []
      perChartParam.value.deviceTheoryRunTime = []
      perChartParam.value.deviceRealRunTime = []
      YIELDChartParam.value.reportTotalCount = []
      YIELDChartParam.value.reportPassCount = []
      OEELineChartParam.value.oee = []
      OEELineChartParam.value.av = []
      OEELineChartParam.value.performance = []
      OEELineChartParam.value.quality = []
      dateList.value = []
      if (res.data && res.data.length > 0) {
        infoLength.value = res.data.length
        res.data.forEach(item => {
          timeChartParam.value.devicePlanRunTime.push(item.devicePlanRunTime);
          timeChartParam.value.deviceRealRunTime.push(item.downTime);
          perChartParam.value.deviceTheoryRunTime.push(item.cycleTime);
          perChartParam.value.deviceRealRunTime.push(item.actualCt);
          YIELDChartParam.value.reportTotalCount.push(item.reportTotalCount);
          YIELDChartParam.value.reportPassCount.push(item.reportFailCount);//NG
          OEELineChartParam.value.oee.push(item.oee);
          OEELineChartParam.value.av.push(item.av);
          OEELineChartParam.value.performance.push(item.performance);
          OEELineChartParam.value.quality.push(item.quality);
          dateList.value.push(item.date.slice(5))
          setOEECharts()
          setTimeChart()
          setPerChart()
          setYIELDChart()
          setOEELineChart()
        });
      }
      console.log(dateList.value);

    })

};
const setOEELineChart = () => {
  if (!OEELineChart.value) return;
  const myChart = echarts.init(OEELineChart.value);
  myChart.setOption({
    grid: {
      show: false, //是否显示直角坐标系网格
      top: '25%', // 距离图例顶部的位置，可写百分比，可以写数字
      right: '5%',
      bottom: '10%',
      left: '5%'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      right: '0',
      top: '0',
      data: [{
        name: 'AV',
        textStyle: {
          color: '#999'
        }
      }, {
        name: 'Perfommance',
        textStyle: {
          color: '#999'
        }
      }, {
        name: 'Quality',
        textStyle: {
          color: '#999'
        }
      }, {
        name: 'OEE',
        textStyle: {
          color: '#999'
        }
      }
      ]
    },
    xAxis: [
      {
        type: 'category',
        data: dateList.value,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        // interval: 25,
        axisLabel: {
          formatter: '{value}' + '%'
        }
      },

      {
        type: 'value',
        name: '',
        interval: 50,
        max: 100,
        splitLine: {
          show: false
        },
        axisLabel: {
          formatter: '{value}' + '%'
        }
      }
    ],
    series: [
      {
        name: 'AV',
        type: 'bar',
        barWidth: '20',
        itemStyle: {
          color: '#0477F4'
        },
        data: OEELineChartParam.value.av
      },
      {
        name: 'Perfommance',
        type: 'bar',
        barWidth: '20',
        itemStyle: {
          color: '#59C6D9'
        },
        data: OEELineChartParam.value.performance
      },
      {
        name: 'Quality',
        type: 'bar',
        barWidth: '20',
        itemStyle: {
          color: '#69DB7E'
        },
        data: OEELineChartParam.value.quality
      },
      {
        name: 'OEE',
        type: 'line',
        yAxisIndex: 1,
        itemStyle: {
          color: '#FFE17F'
        },
        data: OEELineChartParam.value.oee
      }
    ]
  })
}

const setYIELDChart = () => {
  if (!YIELDChart.value) return;
  const myChart = echarts.init(YIELDChart.value);
  myChart.setOption({
    grid: {
      show: false, //是否显示直角坐标系网格
      top: '25%', // 距离图例顶部的位置，可写百分比，可以写数字
      right: '7%',
      bottom: '10%',
      left: '10%'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      right: '0',
      top: '0',
      data: [{
        name: 'Actual total output',
        textStyle: {
          color: '#999'
        }
      }, {
        name: 'Actual NG output',
        textStyle: {
          color: '#999'
        }
      }, {
        name: 'Quality',
        textStyle: {
          color: '#999'
        }
      }
      ]
    },
    xAxis: [
      {
        type: 'category',
        data: dateList.value,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: 'Actual total output',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '',
        interval: 50,
        max: 100,
        splitLine: {
          show: false
        },
        axisLabel: {
          formatter: '{value}' + '%'
        }
      }
    ],
    series: [
      {
        name: 'Actual total output',
        type: 'bar',
        barWidth: '20',
        itemStyle: {
          color: '#0477F4'
        },
        data: YIELDChartParam.value.reportTotalCount
      },
      {
        name: 'Actual NG output',
        type: 'bar',
        barWidth: '20',
        itemStyle: {
          color: '#59C6D9'
        },
        data: YIELDChartParam.value.reportPassCount
      },
      {
        name: 'Quality',
        type: 'line',
        yAxisIndex: 1,
        itemStyle: {
          color: '#FFE17F'
        },
        data: OEELineChartParam.value.quality
      }
    ]
  })
}

const setPerChart = () => {
  if (!perChart.value) return;
  const myChart = echarts.init(perChart.value);
  myChart.setOption({
    grid: {
      show: false, //是否显示直角坐标系网格
      top: '25%', // 距离图例顶部的位置，可写百分比，可以写数字
      right: '7%',
      bottom: '10%',
      left: '10%'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      right: '0',
      top: '0',
      data: [{
        name: 'Target CT',
        textStyle: {
          color: '#999'
        }
      }, {
        name: 'Actual CT',
        textStyle: {
          color: '#999'
        }
      }, {
        name: 'Performance',
        textStyle: {
          color: '#999'
        }
      }
      ]
    },
    xAxis: [
      {
        type: 'category',
        data: dateList.value,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: 'min',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '',
        interval: 50,
        max: 100,
        splitLine: {
          show: false
        },
        axisLabel: {
          formatter: '{value}' + '%'
        }
      }
    ],
    series: [
      {
        name: 'Target CT',
        type: 'bar',
        barWidth: '20',
        itemStyle: {
          color: '#0477F4'
        },
        data: perChartParam.value.deviceTheoryRunTime
      },
      {
        name: 'Actual CT',
        type: 'bar',
        barWidth: '20',
        itemStyle: {
          color: '#59C6D9'
        },
        data: perChartParam.value.deviceRealRunTime
      },
      {
        name: 'Performance',
        type: 'line',
        yAxisIndex: 1,
        itemStyle: {
          color: '#FFE17F'
        },
        data: OEELineChartParam.value.performance
      }
    ]
  })
}
const setTimeChart = () => {
  if (!timeChart.value) return;
  const myChart = echarts.init(timeChart.value);
  myChart.setOption({
    grid: {
      show: false, //是否显示直角坐标系网格
      top: '25%', // 距离图例顶部的位置，可写百分比，可以写数字
      right: '7%',
      bottom: '10%',
      left: '10%'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      right: '0',
      top: '5%',
      data: [{
        name: 'Planned production time',
        textStyle: {
          color: '#999'
        }
      }, {
        name: 'Down time',
        textStyle: {
          color: '#999'
        }
      }, {
        name: 'AV',
        textStyle: {
          color: '#999'
        }
      }
      ]
    },
    xAxis: [
      {
        type: 'category',
        data: dateList.value,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: 'min',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '',
        interval: 50,
        max: 100,
        splitLine: {
          show: false
        },
        axisLabel: {
          formatter: '{value}' + '%'
        }
      }
    ],
    series: [
      {
        name: 'Planned production time',
        type: 'bar',
        barWidth: '20',
        itemStyle: {
          color: '#0477F4'
        },
        data: timeChartParam.value.devicePlanRunTime
      },
      {
        name: 'Down time',
        type: 'bar',
        barWidth: '20',
        itemStyle: {
          color: '#59C6D9'
        },
        data: timeChartParam.value.deviceRealRunTime
      },
      {
        name: 'AV',
        type: 'line',
        yAxisIndex: 1,
        itemStyle: {
          color: '#FFE17F'
        },
        data: OEELineChartParam.value.av
      }
    ]
  })
}
const setOEECharts = () => {
  if (!OEEChart.value) return;
  const color = new echarts.graphic.LinearGradient(0, 0, 1, 0, [
    {
      offset: 0,
      color: '#98F1F1',
    },
    {
      offset: 1,
      color: '#1A75EB',
    },
  ]);
  const colorSet = [
    [0.9, color],
    [1, '#1A75EB']
  ];

  const myChart = echarts.init(OEEChart.value);
  myChart.setOption({

    series: [
      {
        type: 'gauge',
        radius: '100%', // 增加仪表盘的半径以使其更宽
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        center: ['50%', '65%'],
        width: "25px",
        axisLine: {
          lineStyle: {
            width: 15,
            borderRound: 10,
            color: colorSet // 渐变色作为轴的背景色
          }
        },
        pointer: {
          icon: 'path://M12,0a12,12,0,1,0,24,0a12,12,0,1,0,-24,0z', // 这是一个圆形路径
          length: '10%',
          width: 10, // 增加宽度
          offsetCenter: [0, '-88%'], // 向下偏移
          itemStyle: {
            color: "#fff"
          }
        },
        axisTick: {
          show: false
        },
        progress: {
          overlayStyle: {
            stroke: '#91cc75'
          },
          roundCap: true
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          show: false
        },
        detail: {
          formatter: function (value) {
            return `{value|${value}%}\n{sub|OEE}`; // 添加小字"OEE"在新的一行
          },
          offsetCenter: [0, '10%'], // 向上移动detail部分
          rich: {
            value: {
              width: 100, // 设置圆圈的直径
              height: 100, // 设置圆圈的直径
              color: '#035BEB', // 设置文字颜色
              lineHeight: 100, // 设置行高与圆圈直径相同
              backgroundColor: '#EEF4FF', // 设置圆圈背景颜色
              borderRadius: 50, // 设置圆角，与圆圈直径的一半相同
              align: 'center', // 文字居中
              verticalAlign: 'middle', // 文字垂直居中
              fontSize: 20, // 设置字体大小
              fontWeight: 'bold' // 设置字体加粗
            },
            sub: {
              color: '#999', // 设置小字颜色
              fontSize: 13, // 设置小字字体大小
              align: 'center', // 小字居中
              verticalAlign: 'top', // 小字垂直对齐到顶部
              padding: [-25, 0, 10, 0] // 设置小字与上面的文字的间距
            }
          },
          valueAnimation: true // 开启数值动画
        },

        data: [{ value: OEELineChartParam.value.oee[infoLength.value - 1] }]
      }
    ]
  });


  window.addEventListener('resize', () => {
    myChart.resize();
  });
}



const searchParam = ref({
  // date = moment.js 的今天 -1
  date: moment().subtract(1, 'days').format('YYYY-MM-DD')
})
const getTopList = () => {
  axiosInstance.post('/api/oeeReport/top', {
  })
    .then((res) => {
      if (res.code !== 200) {
        ElMessage.warning(res.message);
        return false;
      }
      if (res.data.length > 0) {
        searchParam.value.equipmentId = res.data[0].equipmentId
        getList()
      }
      topTable.value = res.data
    })
}
const deviceList = ref([])
const getOptions = () => {
  axiosInstance.post('/api/basedataEquipment/getAll', {})
    .then((res) => {
      if (res.code !== 200) {
        ElMessage.warning(res.message);
        return false;
      }
      deviceList.value = res.data;
    });
}


</script>
<style scoped lang="scss">
.content {
  display: flex;
  height: 100%; // 确保内容区域占满整个父容器的高度

  .pageLeft {
    width: calc(100% - 400px);
    height: 100%; // 确保左侧区域占满整个内容区域的高度

    .oeeReportSearch {
      background-color: #fff;
      padding: 20px 0 0 10px;
      border-radius: 6px;
    }

    .oeeReportBody {
      margin-top: 10px;
      height: 248px;
      display: flex;
      justify-content: space-between;

      .oeeReportView {
        padding: 10px;
        background-color: #fff;
        width: 49.7%;
        height: 248px;
        border-radius: 6px;
        display: flex;
        flex-direction: column;
      }
    }


  }

  .pageRight {
    width: 445px;
    height: 100%; // 确保右侧区域占满整个内容区域的高度
    margin-left: 10px;

    .oeeTop {
      height: 100%; // 确保排行榜占满整个右侧区域的高度
      padding: 20px 10px;
      background-color: #FFF;
      display: flex;
      border-radius: 6px;
      flex-direction: column;

      .cell {
        width: 25px;
        height: 25px;
        background-color: #D8D8D8;
        display: flex;
        color: #4E5969;
        font-weight: 700;
        font-size: 15px;
        border-radius: 50%;
        align-items: center;
        justify-content: center;
        margin: 11px 0;
      }

      .responsive-image {
        width: 60px;
        height: 60%;
        margin: 11px 0;
        object-fit: cover;
      }
    }
  }
}

.leftTopView {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 35%;

  .left-view {
    margin-bottom: 15px;
    display: flex;
    width: 100%;

    .leftTopView-label {
      color: #999;
      width: 100px;
    }

    .leftTopView-value {
      color: #777;
      font-weight: 700;
    }
  }
}
</style>
